//
//  ShoppingViewController.m
//  YouWen
//
//  Created by Lee GJ on 15-3-9.
//  Copyright (c) 2015年 刘永和. All rights reserved.
//

#import "ShoppingViewController.h"

@interface ShoppingViewController ()

@end

@implementation ShoppingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];
    
    self.shoppingTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100)];
    [self.view addSubview:self.shoppingTableView];
    
    self.shoppingTableView.delegate = self;
    self.shoppingTableView.dataSource = self;
    //创建自己的数组
    self.shoppingArr = [NSMutableArray array];
    //上拉加载 下拉刷新
    //标记上拉操作还是下拉操作，yes为上拉
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    self.offset = 0;



}

- (void)addHeader
{
    
    __block ShoppingViewController *vc = self;
    
    // 添加下拉刷新头部控件
    [self.shoppingTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.offset = 0;
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:0];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.shoppingTableView headerBeginRefreshing];
}
#pragma mark --上拉加载更多
- (void)addFooter
{
    __block ShoppingViewController *vc = self;
    
    
    // 添加上拉刷新尾部控件
    [self.shoppingTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.offset = vc.offset + 10;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.offset];//请求更多数据
        
    }];
}

#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    NSString *url_string = [NSString stringWithFormat:@"http://a.xcar.com.cn/interface/6.0/getNewsList.php?limit=10&offset=%ld&type=4&ver=6.0.3",self.offset];
    
    NSLog(@"url = %@",url_string);
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        
        
        NSDictionary *allDic = responseObject;
        
        
        //        //记录下一页
        //        self.myPage++;
        
        //        NSLog(@"nextCursor == %ld",self.myPage);
        
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.shoppingArr removeAllObjects];
        }
        
        
        NSArray *arr = [allDic objectForKey:@"newsList"];
        for (NSDictionary *dic in arr) {
            Model *shoppingModel = [[Model alloc]init];
            [shoppingModel setValuesForKeysWithDictionary:dic];
            [self.shoppingArr addObject:shoppingModel];
            
        }
        [self.shoppingTableView footerEndRefreshing];//结束底部刷新效果
        [self.shoppingTableView headerEndRefreshing];//结束头部刷新效果
        [self.shoppingTableView reloadData];//刷新tableview
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shoppingArr.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    ShoppingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ShoppingTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    Model *model = [self.shoppingArr objectAtIndex:indexPath.row];
    cell.titleLabel.text = model.newsTitle;
    cell.cateGoryLabel.text = model.newsCategory;
    cell.commentLabel.text = [NSString stringWithFormat:@"%ld", model.commentCount];
    
    //申请图片
    NSString *urlStr = model.newsImage;
    NSString *urlStrEncode = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStrEncode];
    [cell.carImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"a863887815b423588cabcbca8b5fba35.gif"]];
    return cell;
}

//点击cell触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myModel = [self.shoppingArr objectAtIndex:indexPath.row];
    DetailViewController *DetailVC = [[DetailViewController alloc]init];
    DetailVC.model = self.myModel;
    [self.navigationController pushViewController:DetailVC animated:YES];
    
    
    DetailVC.myDelegate = self;
    DetailVC.myDelegate2 = self;
    
    [[DataBaseHandle shareDataBaseHandle]openAndCreatDataBase];
    for (Model *model in [[DataBaseHandle shareDataBaseHandle]selectCar]) {
        //如果数据库里有点击的cell  则变量为YES(已经收藏)
        if ([model.newsTitle isEqualToString:self.myModel.newsTitle]) {
            
            DetailVC.isCollect = YES;
            return;
        }
    }
    //如果数据库里没有点击的cell 则变量为NO(未收藏)
    DetailVC.isCollect = NO;
    
}

- (void)cellect
{
    [[DataBaseHandle shareDataBaseHandle]openAndCreatDataBase];
    for (Model *model in [[DataBaseHandle shareDataBaseHandle]selectCar]) {
        if ([model.newsTitle isEqualToString:self.myModel.newsTitle]) {
            NSLog(@"已经收藏");
            return;
        }
    }
    [[DataBaseHandle shareDataBaseHandle]insertCar:self.myModel];
    
}
//detail里的取消收藏按钮方法
- (void)deleteCar
{
    [[DataBaseHandle shareDataBaseHandle]openAndCreatDataBase];
    [[DataBaseHandle shareDataBaseHandle]deleteCar:self.myModel];
    NSLog(@"取消收藏");
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
